//
//  Array+Extension.swift
//  Array_Extension
//
//  Created by 伟宏 on 2019/10/6.
//  Copyright © 2019 伟宏. All rights reserved.
//

extension Array {
    
    /// 变换
    func wh_Map<T>(transform: (Element) -> T) -> [T] {
        guard !isEmpty else { return [] }
        var array = [T]()

        for obj in self {
            array.append(transform(obj))
        }
        return array
    }
    
    /// 过滤
    func wh_filter(includeElement: (Element) -> Bool) -> [Element] {
        guard !isEmpty else { return [] }
        
        var array = [Element]()
        for obj in self where (includeElement(obj) == true) {
            array.append(obj)
        }
        return array
    }
    
    /// 当判断为真的时候，将元素滤出到结果中。一旦不为真，就将剩余的抛弃
    func wh_prefix<T>(includeElement: (Element) -> T) -> [Any] {
        guard !isEmpty else { return [] }
        
        var array:[Any] = [T]()
        
        for arrayObj in self {
            if includeElement(arrayObj) as? Bool == false { return array }
            array.append(arrayObj)
        }
        return array
    }
    
    
    /// 遍历
    func wh_forEach(transform: (Element) -> Void)  {
         for obj in self { transform(obj) }
    }
    
    /// 将元素合并到一个总和的值中
    func wh_reduce<T>(_ initialResult: T,transform: (T,Element) -> T) -> T {
        var result:T = initialResult
        for arrayObj in self {
            result = transform(result,arrayObj)
        }
        return result
    }
}
